package mongo.db.clients.firsts;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.mongodb.AggregationOutput;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.ServerAddress;

public class Aggregate {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		List<ServerAddress> seeds = new ArrayList<ServerAddress>();

		try {
			seeds.add(new ServerAddress("202.191.136.234", 27017));
//			seeds.add(new ServerAddress("172.31.1.5", 27017));
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		MongoClient client = new MongoClient(seeds);

		DB db = client.getDB("netflowdb");
		DBCollection collection = db.getCollection("netflow_column_list");
		
//		System.out.println(collection.findOne());
		
		DBObject record = collection.findOne();
		
		System.out.println(record.get("timestamp"));
		Date time = (Date) record.get("timestamp");
		System.out.println(time.getTime());
		
		Date time1 = new Date(time.getTime());
		System.out.println("new time " + time1);
		
		System.exit(1);
		DBCollection output = db.getCollection("agg_test");

//		System.out.println("count : " + collection.count());
		
		
		Calendar startTime = Calendar.getInstance();
		startTime.add(Calendar.HOUR_OF_DAY, -1);
		startTime.set(Calendar.MINUTE, 0);
		startTime.set(Calendar.SECOND, 0);
		startTime.set(Calendar.MILLISECOND, 0);
		
		DBObject match_query = new BasicDBObject()
		.append("_id.dikey.routerip", "172.31.4.79")
//		.append("_id.dikey.ifindex", 5)
		.append("_id.rd", startTime.getTime());
		
		DBObject match = new BasicDBObject("$match", match_query);
		System.out.println(startTime.getTime());
		
		System.out.println("find-match : " + collection.find(match_query).count());
		
		DBObject group = new BasicDBObject("$group", new BasicDBObject()
		.append("_id", new BasicDBObject()
			.append("dikey", "$_id.dikey")
			.append("customerid", "$_id.customerid")
			.append("dstport", "$_id.dstport")
			.append("protocol", "$_id.protocol")
			.append("hourCount", "$_id.hourCount")
			.append("rd", "$_id.rd")
		)
		.append("total", new BasicDBObject("$sum" , "$value")));
		
		DBObject sort = new BasicDBObject("$sort", new BasicDBObject("total", -1));
		DBObject limit = new BasicDBObject("$limit", 3);
		
		List<DBObject> pipeline = Arrays.asList(group, sort);
		
//		AggregationOutput result = collection.aggregate(match, (DBObject[]) pipeline.toArray());
		AggregationOutput result = collection.aggregate(match, group, sort, limit);
		System.out.println(result.getCommandResult());
		output.insert((List<DBObject>) result.results());
	}
}
